package com.etbsms.controller;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.etbsms.domain.Role;
import com.etbsms.domain.Users;
import com.etbsms.form.QueryUsersForm;
import com.etbsms.form.UsersForm;
import com.etbsms.security.User;
import com.etbsms.service.IRoleService;
import com.etbsms.service.IUsersService;
import com.etbsms.util.Constants;

@Controller
@RequestMapping(value = "/option/**")
@SuppressWarnings("unused")
public class OptionController {

	@Autowired
	private IRoleService roleService;

	@Autowired
	private IUsersService usersService;
	
	public ModelMap setMainMenu(ModelMap map){
		map.addAttribute("MAINMENU", Constants.MAIN_MENU_OPTION);
		return map;
	}

	@RequestMapping(value = "/option/page/private.htm")
	public String privateSetting(HttpServletRequest req, ModelMap map) {
		Users users = ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsers();		
		setMainMenu(map);	
		map.addAttribute("SUBMENU", 1);
		map.addAttribute("UsersForm", new UsersForm(users));
		return Constants.PAGE_OPTIONPRVT;
	}
	
	@RequestMapping(value = "/option/page/password.htm")
	public String passwordSetting(HttpServletRequest req, ModelMap map) {
		Users users = ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsers();		
		setMainMenu(map);	
		map.addAttribute("SUBMENU", 2);
		map.addAttribute("UsersForm", new UsersForm());
		return Constants.PAGE_OPTIONPPWD;
	}
	
	@RequestMapping(value = "/option/private/update.htm")
	@ResponseBody
	public boolean update(UsersForm form, ModelMap map) {
		Users users = ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsers();	
		users.update(form);
		return usersService.update(users);
	}
	
	@RequestMapping(value = "/option/private/password.htm")
	@ResponseBody
	public int password(UsersForm form, ModelMap map) {
		Users users = ((User)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getUsers();	
		int result = Constants.ERRORMSG_SYSTEM;
		
		if(usersService.get(users.getUsername(), form.getPassword()) != null){
			users.setPassword(form.getNew_password());
			result = usersService.update(users) ? Constants.ERRORMSG_SUCCES : Constants.ERRORMSG_SYSTEM;
		}else{
			result = Constants.ERRORMSG_PASWOD;
		}
		return result;
	}
	
}
